/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tools;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.client.http.GoogleGDataRequest;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.extensions.Reminder;
import com.google.gdata.data.extensions.When;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.openbrew.openbrewrf.Administration;
import com.openbrew.openbrewrf.Employee;
import com.openbrew.openbrewrf.OBAlarm;
import com.openbrew.openbrewrf.OBReminder;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;

/**
 *
 * @author chapmand
 */
public class GoogleCalendar {
    private Administration admin = null;
    
    final String FEEDURL = "https://www.google.com/calendar/feeds/default/owncalendars/full";
    final String INSERTSTART = "http://www.google.com/calendar/feeds/";
    final String INSERTSTOP = "/private/full";
    final String BREWHOUSE_ENTRY = "OpenBrew Reminder";
    
    private String errorMsg = "No Errors";
        
    private void loadAdmin(EntityManager en){
        admin = en.createNamedQuery("Administration.findAll", Administration.class).getResultList().get(0);
    }
    
    private String decryptEmployeeEmailPassword(final String encStr){
        String decrypted = Encrypter.NAGASAKTI.decrypt(encStr);
        return decrypted;
    }
    
    private CalendarService getCalendarService(final Employee emp){
        CalendarService myService = new CalendarService("OB-openBrewRF-v1");
        try {
            myService.setUserCredentials(emp.getEmpEmail(), decryptEmployeeEmailPassword(emp.getEmpEmailPass()));
        } catch(AuthenticationException e){
        }
        return myService;
    }
    
    private void insertCalendarEntry(final CalendarEventEntry myEntry ,final CalendarService myService, final Employee emp){
        try{
            URL insertURL = new URL(INSERTSTART+emp.getEmpEmail()+INSERTSTOP);
            myService.insert(insertURL, myEntry);
        } catch(MalformedURLException e){
        } catch(IOException e){
        } catch(ServiceException e){
        }
    }
    
    static void printLongerTrace(Throwable t){
        for(StackTraceElement e: t.getStackTrace()){
            System.out.println(e);
        }
    }
    
    private void appendReminderTaskCalendar(final java.util.Date date, final String calStr, final Employee emp){
        //Check to see if google calendars in enabled in the system.
        if(admin.getBGoogleCal()){
            if((!decryptEmployeeEmailPassword(emp.getEmpEmailPass()).equals("")&&(!emp.getEmpEmail().equals("")))){
                CalendarService myService = getCalendarService(emp);
                if(!calStr.equals("")) {
                    CalendarEventEntry myEntry = createBrewhouseEntry(calStr, date);
                    insertCalendarEntry(myEntry, myService, emp);
                }
            }
        }
    }
    
    private CalendarEventEntry createBrewhouseEntry(final String calStr, final java.util.Date newDate){
        CalendarEventEntry myEntry = new CalendarEventEntry();
        myEntry.setTitle(new PlainTextConstruct(BREWHOUSE_ENTRY));
        myEntry.setContent(new PlainTextConstruct(calStr));
        
        Calendar calStart = Calendar.getInstance(TimeZone.getTimeZone("MST"));
        calStart.setTime(newDate);
        calStart.add(Calendar.HOUR_OF_DAY, -7);
        calStart.set(Calendar.SECOND, 0);
        calStart.set(Calendar.MILLISECOND, 0);  
        DateTime startTime = new DateTime(calStart.getTime());
        
        calStart.add(Calendar.HOUR_OF_DAY, 1);  
        DateTime stopTime = new DateTime(calStart.getTime());
        
        When eventTimes = new When();
        eventTimes.setStartTime(startTime);
        eventTimes.setEndTime(stopTime);
        myEntry.addTime(eventTimes);
        
        //By default two reminders are created a 240 Minute email reminder
        int reminderMinutes = 240;
        Reminder.Method methodType = Reminder.Method.EMAIL;
        Reminder reminder = new Reminder();
        reminder.setMinutes(reminderMinutes);
        reminder.setMethod(methodType);
        myEntry.getReminder().add(reminder);
        
        // 1 hour alert reminder.
        reminderMinutes = 60;
        methodType = Reminder.Method.ALERT;
        Reminder reminder2 = new Reminder();
        reminder2.setMinutes(reminderMinutes);
        reminder2.setMethod(methodType);
        myEntry.getReminder().add(reminder2);
        
        return myEntry;
    }
    
    public void createReminderCalendarEntry(final OBReminder rmdr, final OBAlarm alarm, final Date date, EntityManager en){
        loadAdmin(en);
        System.setProperty(GoogleGDataRequest.DISABLE_COOKIE_HANDLER_PROPERTY, "true");
        
        final String calStr = "Task: " + rmdr.getReminderText() + "\n"
                + "Notes: " + alarm.getAlarmText();
        if(alarm.getEmployeeCollection()!=null){
            for(Employee emp : alarm.getEmployeeCollection()){
                appendReminderTaskCalendar(date, calStr, emp);
            }
        }
    }
}
